package online.afeibaili.storebackendframework.interceptor

import jakarta.mail.internet.MimeMessage
import kotlinx.html.body
import kotlinx.html.div
import kotlinx.html.h3
import kotlinx.html.head
import kotlinx.html.html
import kotlinx.html.stream.createHTML
import kotlinx.html.style
import kotlinx.html.unsafe
import online.afeibaili.storebackendframework.util.message
import online.afeibaili.storebackendframework.util.response
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import java.io.PrintWriter
import java.io.StringWriter
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/**
 * 控制器异常拦截器
 *
 *@author AfeiBaili
 *@version 2025/11/12 23:29
 */

@ControllerAdvice
class ExceptionInterceptor {

    @Autowired
    lateinit var mailSender: JavaMailSender

    @ExceptionHandler(Exception::class)
    fun exceptionHandler(exception: Throwable) = response {
        val mimeMessage: MimeMessage = mailSender.createMimeMessage()

        exception.printStackTrace()

        val stringWriter = StringWriter()
        val datetime: String = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        exception.printStackTrace(PrintWriter(stringWriter))
        val html: String = createHTML().html {
            head {
                style {
                    unsafe {
                        +"""
                            .title,
                            .background {
                                margin: 0 auto;
                                width: 1000px;
                                background-color: #1E1F22;
                                white-space: pre;
                                color: #F75464;
                                padding: 20px;
                                overflow-x: auto;
                                border-radius: 10px;
                                margin-bottom: 10px;
                            }
                        """.trimIndent()
                    }
                }
            }

            body {
                h3("title") {
                    +"$datetime 错误信息：${exception.message}"
                }

                div("background") {
                    +stringWriter.toString()
                }
            }
        }

        MimeMessageHelper(mimeMessage, true).apply {
            setFrom("afeibaili@qq.com")
            setTo("afeibaili@foxmail.com")
            setSubject("滴滴~ 对方不想理你ヾ(≧へ≦)〃~，并且发送了一个错误栈~")
            setText(html, true)
        }

        mailSender.send(mimeMessage)

        500 message "服务器出现了错误"
    }
}